﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Weber.CS3280.Inventory.Logic.Utility;

namespace Weber.CS3280.Inventory.Logic
{
	/// <summary>
	/// The InventoryItemsListController manager persistence and change state 
	/// for inventory items. Later on when we migrate to using a database
	/// this object will become obsolete and we'll replace with other code
	/// </summary>
	public class InventoryItemsListController
	{
		private List<InventoryItemController> _items = new List<InventoryItemController>(25);
		private bool _isDirty;

		public InventoryItemsListController()
		{
		}

		public InventoryItemsListController(string fileName)
		{
		}

		public void AddItem(InventoryItemController item)
		{
			if (item == null)
				return;

			// Add the item to the list
			_items.Add(item);
			// Subscribe to listen to its change notifications
			item.PropertyChanged += OnItemChanged;
			// flag this instance as dirty
			_isDirty = true;
		}

		public void RemoveItem(InventoryItemController item)
		{
			if (item == null)
				return;

			// Unsubscribe from the notification event
			item.PropertyChanged -= OnItemChanged;
			// Remove the item from the list
			_items.Remove(item);
		}

		/// <summary>
		/// Gets an Array of InventoryItemController
		/// </summary>
		// 09/23/2013 - Changed to Array instead of IEnumerable
		public IEnumerable<InventoryItemController> Items
		{
			get
			{
				return _items;
					//.ToArray;
			}
		}

		/// <summary>
		/// Retrieves an item by item code
		/// </summary>
		/// <param name="itemCode">Item code to retrieve</param>
		/// <returns>Reference to the found InventoryItemController, or null
		/// if it is not found</returns>
		public InventoryItemController GetItem(int itemCode)
		{
			return _items
				.FirstOrDefault(item => item.ItemCode == itemCode);
		}

		/// <summary>
		/// Event handler that gets called every time a property of 
		/// InventoryItemController changes
		/// </summary>
		/// <param name="sender">Object that changed</param>
		/// <param name="e">EventArgs that describe the field that changed</param>
		private void OnItemChanged(object sender, PropertyChangedEventArgs e)
		{
			// Optimistically, we're going to expect that we should just make
			// this instance dirty
			IsDirty = true;
		}

		public bool IsDirty 
		{
			get { return _isDirty; }
			private set { _isDirty = value; }
		}

		public void ClearItems()
		{
			_items.Clear();
			IsDirty = true;
		}
	}
}
